package main;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.border.TitledBorder;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import javax.swing.Action;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.DefaultComboBoxModel;

public class bott_order extends JFrame {

	private JPanel contentPane;
	private JTextField textField;
	private final Action action = new SwingAction();
	private final Action action_1 = new SwingAction_1();

	/**
	 * Launch the application.
	 */
	private int ID_li;
	private JComboBox comboBox;
	public static void main(int ID_l) {
		final int ID_ls=ID_l;
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					bott_order frame = new bott_order(ID_ls);
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public bott_order(int ID_l) {
		ID_li=ID_l;
		setResizable(false);
		setTitle("Bottling Order");
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 336, 314);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JLabel lblNewLabel = new JLabel("New Bottling Order");
		lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 16));
		lblNewLabel.setBounds(10, 11, 169, 20);
		contentPane.add(lblNewLabel);
		
		JPanel panel = new JPanel();
		panel.setBorder(new TitledBorder(null, "Parameters", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel.setBounds(30, 42, 252, 97);
		contentPane.add(panel);
		panel.setLayout(null);
		
		JLabel lblMaxProdWhite = new JLabel("Max Prod. White: ");
		lblMaxProdWhite.setBounds(31, 72, 96, 14);
		panel.add(lblMaxProdWhite);
		
		JLabel lblMaxProd = new JLabel("Max Prod. Red : ");
		lblMaxProd.setBounds(31, 48, 81, 14);
		panel.add(lblMaxProd);
		
		JLabel lblLine = new JLabel("Line :");
		lblLine.setBounds(31, 23, 46, 14);
		panel.add(lblLine);
		
		JPanel panel_1 = new JPanel();
		panel_1.setBorder(new TitledBorder(null, "Bottling Order", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel_1.setBounds(30, 150, 252, 76);
		contentPane.add(panel_1);
		panel_1.setLayout(null);
		
		JLabel lblNewLabel_1 = new JLabel("Wine");
		lblNewLabel_1.setBounds(31, 23, 46, 14);
		panel_1.add(lblNewLabel_1);
		
		JLabel lblNewLabel_2 = new JLabel("Quantity");
		lblNewLabel_2.setBounds(31, 48, 46, 14);
		panel_1.add(lblNewLabel_2);
		
		comboBox = new JComboBox();
		comboBox.setModel(new DefaultComboBoxModel(new String[] {"Select Wine", "White", "Red"}));
		comboBox.setBounds(87, 20, 86, 20);
		panel_1.add(comboBox);
		
		textField = new JTextField();
		textField.setBounds(87, 45, 86, 20);
		panel_1.add(textField);
		textField.setColumns(10);
		
		JButton btnNewButton = new JButton("New button");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
			}
		});
		btnNewButton.setAction(action);
		btnNewButton.setBounds(30, 242, 111, 23);
		contentPane.add(btnNewButton);
		
		JButton btnNewButton_1 = new JButton("New button");
		btnNewButton_1.setAction(action_1);
		btnNewButton_1.setBounds(187, 242, 111, 23);
		contentPane.add(btnNewButton_1);
	}
	private class SwingAction extends AbstractAction {
		public SwingAction() {
			putValue(NAME, "Generate Order");
			putValue(SHORT_DESCRIPTION, "Some short description");
		}
		public void actionPerformed(ActionEvent e) {
			int[][] setup = new int [2][2];
			 
		    try {
		    	String query = "SELECT de, a, tiempo FROM setup_times";
		    	 Connection conn =  connect.connect_DB();
		  		 PreparedStatement ps = conn.prepareStatement(query);
		  		 ResultSet rs = ps.executeQuery();
		  		while ( rs.next() ) {
		  		setup[rs.getInt(1)-1][rs.getInt(2)-1] = rs.getInt(3);
		  		}
		    	rs.close();
		    	ps.close();
		    	
		  	    query = "SELECT Sem, tipo, Seq FROM bottling WHERE ((ID_Game=?) AND (Sem>=?) AND (Line=?)) Order By Sem ASC, Seq ASC";
		  		 int prev_tip =0;
		  		 int sema=0;
		  		 int Sequ=0;
		  		 int Setu=0;
		  		 boolean val=true;
		  		  ps = conn.prepareStatement(query);
		  		  ps.setInt(1, values.getIDGame());
		  		  ps.setInt(2, values.getWeek()-1);
		  		  ps.setInt(3, ID_li);
		  		  rs = ps.executeQuery();
		  		  while ( rs.next() ) {
		  				  prev_tip = rs.getInt(2);
		  				  sema = rs.getInt(1);
		  				  Sequ = rs.getInt(3);
		  		  }
		  		rs.close();
		    	ps.close();
		    	//Check setup Time is OK
		    	if (comboBox.getSelectedIndex()==1){
		    		if (prev_tip==0) {
		    			Setu=0;
		    		} else {
		    		Setu = setup[prev_tip-1][0];
		    		}
  				} else if (comboBox.getSelectedIndex()==2) {
  					if (prev_tip==0) {
		    			Setu=0;
		    		} else {
  					Setu = setup[prev_tip-1][1];
		    		}
  				} else {
  					//select Value
  					val=false;
  				}
		    	query = "SELECT SUM(Prod), SUM(Setup) FROM bottling WHERE ((ID_Game=?) AND (Sem=?) AND (Line=?))";
		    	ps = conn.prepareStatement(query);
		  		  ps.setInt(1, values.getIDGame());
		  		  ps.setInt(2, values.getWeek());
		  		  ps.setInt(3, ID_li);
		  		  rs = ps.executeQuery();
		  		  while ( rs.next() ) {
		  			  if ((rs.getInt(1)+rs.getInt(2)+Integer.parseInt(textField.getText())+Setu)>10){
		  				val=false;
		  				JOptionPane.showMessageDialog( null,
					            "The production + setup time exceeds total available time. Change production!",
					            "Error", JOptionPane.ERROR_MESSAGE);
		  			  } 
		  		  }
		  	    query = "INSERT INTO bottling (ID_Game, Sem, Line, Seq, Tipo, quant, prod, setup) VALUES (?,?,?,?,?,?,?,?)";
  				 ps = conn.prepareStatement(query);
		  		ps.setInt(1, values.getIDGame());
		  		ps.setInt(2, values.getWeek());
		  		ps.setInt(3, ID_li);
		  		if (sema==values.getWeek()) {
		  		ps.setInt(4,Sequ+1);
		  		} else {
		  			ps.setInt(4,0);
		  		}
  				if (comboBox.getSelectedIndex()==1){
  					ps.setInt(5,1);
  					if (prev_tip==0) {
		    			Setu=0;
		    			ps.setInt(8, 0);
		    		} else {
  					ps.setInt(8, setup[prev_tip-1][0]);
		    		}
  				} else if (comboBox.getSelectedIndex()==2) {
  					ps.setInt(5,2);
  					if (prev_tip==0) {
		    			Setu=0;
		    			ps.setInt(8, 0);
		    		} else {
  					ps.setInt(8, setup[prev_tip-1][1]);
		    		}
  				} else {
  					JOptionPane.showMessageDialog( null,
				            "Select a type of wine!",
				            "Error", JOptionPane.ERROR_MESSAGE);
  					val=false;
  				}
  				if (Integer.parseInt(textField.getText())>=0) {
  					ps.setInt(6,Integer.parseInt(textField.getText()));
  				} else {
  					JOptionPane.showMessageDialog( null,
				            "Enter valid production!",
				            "Error", JOptionPane.ERROR_MESSAGE);
  					val=false;
  				}
  				if (Integer.parseInt(textField.getText())>=0) {
  					ps.setInt(7,Integer.parseInt(textField.getText()));
  				} else {
  					JOptionPane.showMessageDialog( null,
				            "Enter valid production!",
				            "Error", JOptionPane.ERROR_MESSAGE);
  					val=false;
  				}
  				if (val){
  				ps.execute();
  				JOptionPane.showMessageDialog( null,
			            "Order created succesfully!",
			            "Order", JOptionPane.INFORMATION_MESSAGE);
  				dispose();
  				}
  				 ps.close();
				 conn.close();
		  		}
			
					  catch (Exception ex) {
				            Logger.getLogger(bott_order.class.getName()).log(Level.SEVERE, null, ex);
				        
				  }
			
			
			
		}
	}
	private class SwingAction_1 extends AbstractAction {
		public SwingAction_1() {
			putValue(NAME, "Close Window");
			putValue(SHORT_DESCRIPTION, "Some short description");
		}
		public void actionPerformed(ActionEvent e) {
			dispose();
		}
	}
}
